package immutablecollections;

public class ImTreeFactory
{
    private ImList<String> list;

    public ImTreeFactory(final String string)
    {
        list = string.length() == 0
                ? ImList.<String> empty()
                : ImList.onArray(string.split(" +"));
    }

    private Character getLabel(final String top)
    {
        return top.charAt(0);
    }

    private ImTree<Character> makeNode(final int expectedLevel)
    {
        if (list.isEmpty())
        {
            return ImTree.Nil();
        }

        if (getLevel(list.head()) != expectedLevel)
        {
            return ImTree.Nil();
        }

        final Character label = getLabel(list.head());

        list = list.tail(); // A bit clunky

        if (label.equals('-'))
        {
            return ImTree.Nil();
        }

        final ImTree<Character> left = makeNode(expectedLevel + 1);
        final ImTree<Character> right = makeNode(expectedLevel + 1);

        return new ImTree<Character>(label, left, right);
    }

    private int getLevel(final String top)
    {
        return Integer.parseInt(top.substring(1));
    }

    public ImTree<Character> create()
    {
        return makeNode(1);
    }

}
